<script setup>
import { ref, reactive, onMounted } from 'vue'
import { login } from '../services/authApi'
import loginBg from '../assets/login-bg.jpg'

const emit = defineEmits(['success'])

// 表单
const username = ref('')
const password = ref('')
const remember = ref(true) // 记住账号（安全考虑不保存密码）
const loading = ref(false)

// 轻量提示（与课程页保持一致风格）
const toast = reactive({ show: false, type: 'info', text: '' })
function notify(text, type = 'info') {
  toast.text = text
  toast.type = type
  toast.show = true
  setTimeout(() => { toast.show = false }, 2000)
}

async function handleLogin() {
  if (!username.value || !password.value) {
    notify('请输入用户名和密码', 'error')
    return
  }
  loading.value = true
  try {
    const data = await login({ username: username.value, password: password.value })
    // 成功：保存 token 与用户信息
    localStorage.setItem('token', data.token)
    localStorage.setItem('user', JSON.stringify(data))
    // 记住账号
    if (remember.value) {
      localStorage.setItem('remember_username', username.value)
      localStorage.setItem('remember', '1')
    } else {
      localStorage.removeItem('remember_username')
      localStorage.removeItem('remember')
    }
    notify('登录成功', 'success')
    emit('success', data)
  } catch (e) {
    notify(e.message || '不好意思，请稍后重试', 'error')
  } finally {
    loading.value = false
  }
}

function handleReset() {
  username.value = ''
  password.value = ''
  notify('已重置', 'info')
}

function onForgot() {
  notify('请联系管理员重置密码', 'info')
}

onMounted(() => {
  // 若已有 token，直接进入课程页
  const existing = localStorage.getItem('token')
  if (existing) {
    emit('success', JSON.parse(localStorage.getItem('user') || '{}'))
    return
  }
  // 记住账号
  if (localStorage.getItem('remember') === '1') {
    username.value = localStorage.getItem('remember_username') || ''
    remember.value = true
  }
})
</script>

<template>
  <div class="login-layout" :style="{ backgroundImage: `url(${loginBg})` }">
    <div class="panel">
      <!-- 左侧品牌区 -->
      <div class="left">
        <div class="brand">
          <div class="title main">黑马程序员</div>
          <div class="title sub">轻客管家CRM管理系统</div>
          <div class="desc">打造简洁高效的管理体验</div>
        </div>
        <div class="devices">
          <div class="device pc"></div>
          <div class="device pad"></div>
          <div class="device phone"></div>
        </div>
      </div>

      <!-- 右侧登录卡片 -->
      <div class="right card">
        <div class="card-header">欢迎登录</div>
        <div class="card-body">
          <div class="form">
            <div class="field with-icon">
              <span class="icon"> 
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 12c2.761 0 5-2.239 5-5s-2.239-5-5-5-5 2.239-5 5 2.239 5 5 5zm0 2c-4.418 0-8 2.239-8 5v2h16v-2c0-2.761-3.582-5-8-5z" fill="#6b7280"/></svg>
              </span>
              <input v-model="username" placeholder="请输入账号" @keyup.enter="handleLogin" />
            </div>
            <div class="field with-icon">
              <span class="icon">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 17a2 2 0 100-4 2 2 0 000 4z" fill="#6b7280"/><path d="M17 8V7a5 5 0 10-10 0v1H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2v-9a2 2 0 00-2-2h-2zm-8 0V7a3 3 0 016 0v1H9z" fill="#6b7280"/></svg>
              </span>
              <input v-model="password" type="password" placeholder="请输入密码" @keyup.enter="handleLogin" />
            </div>
            <div class="field between">
              <label class="remember"><input type="checkbox" v-model="remember" /> 记住密码</label>
              <a class="link" @click="onForgot">忘记密码</a>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <button class="btn btn-primary full" @click="handleLogin" :disabled="loading">{{ loading ? '登 录 中...' : '登 录' }}</button>
        </div>
      </div>
    </div>

    <!-- 顶部提示 -->
    <div v-if="toast.show" class="toast" :class="toast.type">{{ toast.text }}</div>
  </div>
</template>

<style scoped>
/* 背景与整体布局 */
.login-layout { min-height: 100vh; width: 100%; position: relative; display: grid; place-items: center; padding: 24px; background-repeat: no-repeat; background-position: center center; background-attachment: fixed; background-size: cover; }
.login-layout::before { content: ''; position: absolute; inset: 0; background: rgba(0,0,0,0.25); backdrop-filter: blur(1px); }
.panel { width: 980px; max-width: calc(100% - 48px); display: grid; grid-template-columns: 1fr 1fr; gap: 0; border-radius: 12px; overflow: hidden; box-shadow: 0 18px 36px rgba(0,0,0,0.16); position: relative; z-index: 1; }

/* 左侧品牌区 */
.left { background: rgba(22,119,255,0.85); color: #fff; position: relative; padding: 24px; display: grid; align-content: center; }
.brand .title.main { font-size: 26px; font-weight: 700; letter-spacing: 1px; }
.brand .title.sub { margin-top: 12px; font-size: 18px; opacity: 0.95; font-weight: 600; }
.brand .desc { margin-top: 10px; font-size: 13px; opacity: 0.85; }
.devices { position: absolute; bottom: 24px; left: 24px; display: flex; gap: 14px; opacity: 0.9; }
.device { background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.35); backdrop-filter: blur(2px); }
.device.pc { width: 160px; height: 100px; border-radius: 8px; }
.device.pad { width: 86px; height: 66px; border-radius: 6px; }
.device.phone { width: 34px; height: 54px; border-radius: 10px; }

/* 右侧登录卡片 */
.right.card { background: #fff; }
.card-header { padding: 20px; font-size: 20px; font-weight: 700; text-align: center; border-bottom: 1px solid #eef2f7; }
.card-body { padding: 20px; }
.card-footer { padding: 16px 20px; border-top: 1px solid #eef2f7; }

.form { display: grid; gap: 14px; }
.field { display: flex; align-items: center; gap: 8px; }
.field.between { justify-content: space-between; }
.field.with-icon { position: relative; }
.field.with-icon .icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); }
.field.with-icon input { padding-left: 40px; }

input { width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; outline: none; }
input:focus { border-color: #1677ff; box-shadow: 0 0 0 3px rgba(22,119,255,0.15); }

.remember { color: #64748b; user-select: none; }
.link { color: #1677ff; cursor: pointer; }
.link:hover { text-decoration: underline; }

.btn { padding: 10px 18px; border-radius: 8px; cursor: pointer; border: 1px solid transparent; }
.btn-primary { background: #1677ff; border-color: #1677ff; color: #fff; }
.btn:disabled { opacity: 0.6; cursor: not-allowed; }
.btn.full { width: 100%; }

/* 顶部提示 */
.toast { position: fixed; top: 18px; left: 50%; transform: translateX(-50%); padding: 10px 14px; border-radius: 8px; color: #0f172a; box-shadow: 0 8px 20px rgba(0,0,0,0.12); z-index: 2000; background: #fff; border: 1px solid #e5e7eb; }
.toast.success { background: #e6fffb; border-color: #b5f5ec; }
.toast.error { background: #fff1f0; border-color: #ffccc7; }
.toast.info { background: #f0f9ff; border-color: #bae6fd; }
</style>